#!/usr/bin/env python3

import time
import backtrader as bt
import datetime as dt
import baostock as bs
import pandas as pd
import tushare as ts
from decimal import Decimal
import math
import numpy as np
import datetime
import matplotlib.pyplot as plt
#from ccxtbt import CCXTStore
from config import BINANCE, ENV, PRODUCTION, COIN_TARGET, COIN_REFER, DEBUG
import pymysql

from dataArrangeAi.Strategies.aiStrategy import aiStrategy
from dataArrangeAi.Strategies.aiStrategy5r import aiStrategy5r
from dataset.dataset import CustomDataset
from nowStrategies.BollNowM import BollNowM
from nowStrategies.SM25 import SM25
from nowStrategies.HigBiLi import HigBiLi
from nowStrategies.SM25Two import SM25Two
from nowStrategies.YesterdayKeyPointsStrategy import YesterdayKeyPointsStrategy
from nowStrategies.nowBehindKeyPointsStrategy import nowBehindKeyPointsStrategy
from nowStrategies.nowKeyPointsStrategy import nowKeyPointsStrategy
from nowStrategies.nowTimeBehindtrategy import nowTimeBehindtrategy
from sizer.percent import FullMoney
from strategies.AlphaPortfolioStrategy import AlphaPortfolioStrategy
from strategies.AverageStrategy import AverageStrategy
from strategies.MyStrategy import MyStrategy
from strategies.SsaStrategy import SsaStrategy
from strategies.TailPlateStrategy import TailPlateStrategy
from strategies.TestStrategy import TestStrategy
from strategies.base import StrategyBase
from strategies.basic_rsi import BasicRSI
from strategies.boll import Boll
from util.GetBaostockDat import GetBaostockDat
from util.GetTushareDat import GetTushareDat
from utils import print_trade_analysis, print_sqn, send_telegram_message
'''
根据已有策略，计算当前行情符合策略的股票
'''
def main():

    fromdate = datetime.datetime(1990, 7, 1)
    todate = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day)

    lg = bs.login(user_id='anonymous', password='123456')
    pro = ts.pro_api(token='936d1029be68a59a3e77eeb9e4eb1ea3c36502bd4b4bf9e1aae91bd8')
    # 打开数据库连接
    db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='financialdata', charset='utf8')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    sSql = """select * from shares """
    cursor.execute(sSql)
    sResults = cursor.fetchall()

    if (len(sResults) > 0):
        for row in sResults:
            try:
                cerebro = bt.Cerebro(quicknotify=True)
                code = row[5]
                date = '1990-01-01'
                print(code)
                data = GetTushareDat().getData(pro, code, date, 'd', fromdate, todate)
                cerebro.adddata(data)
                data = GetTushareDat().getData(pro, code, date, 'w', fromdate, todate)
                cerebro.adddata(data)
                broker = cerebro.getbroker()
                broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                broker.setcash(10000.0)  #
                cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                #nowTime = nowTimeBehindtrategy()
                cerebro.addstrategy(aiStrategy5r)
                cerebro.run()
            except Exception as err:
                1 + 1
            # print("Finished with error: ", err)
    print("运行完成!")




if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("finished.")
        time = dt.datetime.now().strftime("%d-%m-%y %H:%M")
        send_telegram_message("Bot finished by user at %s" % time)
    except Exception as err:
        send_telegram_message("Bot finished with error: %s" % err)
        print("Finished with error: ", err)
        raise